using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Os.WebUI.Models;

namespace Os.WebUI.Controllers
{
	[HandleError]
	public class AccountController : Controller
	{
		public IFormsAuthenticationService FormsService { get; set; }
		public IMembershipService MembershipService { get; set; }
		
        protected override void Initialize(RequestContext requestContext)
		{
			if (this.FormsService == null)
			{
				this.FormsService = new FormsAuthenticationService();
			}
			if (this.MembershipService == null)
			{
				this.MembershipService = new AccountMembershipService();
			}
			base.Initialize(requestContext);
		}
		public ActionResult LogOn()
		{
            return View();
		}
		[HttpPost]
		public ActionResult LogOn(LogOnModel model, string returnUrl)
		{
			if (ModelState.IsValid)
			{
				if (this.MembershipService.ValidateUser(model.UserName, model.Password))
				{
					this.FormsService.SignIn(model.UserName, model.RememberMe);
					if (!string.IsNullOrEmpty(returnUrl))
					{
						return Redirect(returnUrl);
					}
                    if (User.IsInRole("Cliente"))
                    {
                        return RedirectToAction("AberturaOrdemServico", "OrdemServico");
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
				}
				else
				{
					ModelState.AddModelError("", "O usuário ou a senha informado estão incorretos.");
				}
			}
			return View(model);
		}
		public ActionResult LogOff()
		{
			this.FormsService.SignOut();
			return RedirectToAction("LogOn", "Account");
		}

		[Authorize(Roles = "Administrador")]
		public ActionResult Register()
		{
			ViewData["PasswordLength"] = this.MembershipService.MinPasswordLength;
			return View();
		}
		
        [HttpPost, Authorize(Roles = "Administrador")]
        public ActionResult Register(RegisterModel model)
		{
			if (ModelState.IsValid)
			{
				MembershipCreateStatus membershipCreateStatus = this.MembershipService.CreateUser(model.UserName, model.Password, model.Email);
				if (membershipCreateStatus == MembershipCreateStatus.Success)
				{
					Roles.AddUserToRole(model.UserName, "Administrador");
					return RedirectToAction("Index", "Home");
				}
				ModelState.AddModelError("", AccountValidation.ErrorCodeToString(membershipCreateStatus));
			}
			ViewData["PasswordLength"] = this.MembershipService.MinPasswordLength;
			return View(model);
		}
		[Authorize(Roles = "Administrador,Cliente")]
		public ActionResult ChangePassword()
		{
			ViewData["PasswordLength"] = this.MembershipService.MinPasswordLength;
			return View();
		}
		[HttpPost, Authorize(Roles = "Administrador,Cliente")]
		public ActionResult ChangePassword(ChangePasswordModel model)
		{
			if (ModelState.IsValid)
			{
				if (this.MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
				{
					return RedirectToAction("ChangePasswordSuccess");
				}
				ModelState.AddModelError("", "A nova senha está incorreta ou a nova senha é inválida.");
			}
			ViewData["PasswordLength"] = this.MembershipService.MinPasswordLength;
			return View(model);
		}
		[Authorize(Roles = "Administrador,Cliente"),HttpGet]
		public ActionResult ChangePasswordSuccess()
		{
			return View();
		}
		public JsonResult RoleOn()
		{
			List<string> data = Roles.GetRolesForUser(User.Identity.Name).ToList<string>();
			return Json(data, JsonRequestBehavior.AllowGet);
		}
	}
}
